import {
  addMaterialFile,
  deleteMaterialFile,
  materialFileList,
} from '@/services/MaterialFileService';
import { RecordFile } from '@/types';
import { useModel } from '@@/exports';
import {
  DeleteOutlined,
  DownloadOutlined,
  ReloadOutlined,
  UploadOutlined,
} from '@ant-design/icons';
import { ProFormRadio, ProFormText, QueryFilter } from '@ant-design/pro-form';
import {
  Button,
  Col,
  Image,
  Popconfirm,
  Row,
  Upload,
  UploadProps,
  message,
} from 'antd';
import { useEffect, useState } from 'react';
import styles from './index.less';

const MaterialFile = () => {
  const { patient, setPatient } = useModel('patient');
  const [_message, contextHolder] = message.useMessage();
  const { peerServer, panServer } = useModel('global');
  const [list, setList] = useState<RecordFile[]>([]);
  const [searchParams, setSearchParams] = useState<any>({
    type: 'video',
    userId: patient?.id,
  });

  const loadFileList = () => {
    try {
      materialFileList(peerServer, searchParams).then(({ data }) => {
        if (data.success) {
          setList(data.data);
        }
      });
    } catch {
      _message.error('连接服务器失败');
    }
  };

  const props: UploadProps = {
    multiple: false,
    method: 'post',
    headers: {
      Authorization:
        'Bearer ' +
        localStorage.getItem('token')?.replaceAll('"', '') +
        ' ' +
        localStorage.getItem('tokenIssueTime'),
    },
    onChange: async (info) => {
      console.log('info', info);
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        _message.success(`${info.file.name} 上传成功`);
        const fileData = info.file.response.data;
        fileData.userId = patient?.id;
        fileData.type = searchParams.type;
        fileData.fileName = decodeURI(fileData.fileName);
        fileData.fileUrl = decodeURI(fileData.fileUrl);
        const { data } = await addMaterialFile(peerServer, fileData);
        if (data.success) {
          loadFileList();
        }
      } else if (info.file.status === 'error') {
        _message.error(`${info.file.name} 上传失败`);
      }
    },
  };
  useEffect(loadFileList, [searchParams]);
  useEffect(() => {
    setSearchParams({
      type: searchParams.type,
      userId: patient?.id,
    });
  }, [patient]);
  return (
    <div
      style={{
        userSelect: 'none',
        padding: '20px',
        height: '100%',
      }}
    >
      {contextHolder}
      <div
        style={{
          background: 'rgba(25, 38, 86, 0.9)',
          marginBlockEnd: '16px',
          borderRadius: '6px',
          height: '80px',
        }}
      >
        <QueryFilter<{
          search: string;
          searchTime: any;
          type: string;
        }>
          initialValues={{
            type: 'video',
            userId: patient?.id,
          }}
          // onFinish={async (params) => {
          //   // console.log(params);
          //   setSearchParams((f: any) => ({ ...f, ...params }));
          // }}
          onValuesChange={(changedValues, allValues) => {
            // console.log(allValues);
            setSearchParams((f: any) => ({ ...f, ...allValues }));
          }}
          submitter={{
            render: () => {
              return [
                <Upload
                  key="upload"
                  name="file"
                  action={`${peerServer}/api/file/upload`}
                  data={searchParams}
                  showUploadList={false}
                  accept={
                    searchParams.type === 'video'
                      ? 'video/*'
                      : searchParams.type === 'pic'
                      ? 'image/*'
                      : searchParams.type === 'document'
                      ? '.doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                      : undefined
                  }
                  beforeUpload={(file: any, fileList: any) => {
                    console.log('file', file);
                    debugger;
                    // 后缀获取
                    var suffix = '';
                    // 获取类型结果
                    var result = false;
                    try {
                      if (file) {
                        var fileArr = file.name.split('.');
                        suffix = fileArr[fileArr.length - 1];
                      } else {
                        suffix = '';
                      }
                    } catch (err) {
                      message.error('文件类型上传错误！');
                      return false;
                    }
                    if (searchParams.type == 'video') {
                      var typeList = ['mp4', 'm2v', 'mkv', 'mp3', 'wav', 'wmv'];
                      // 进行图片匹配
                      result = typeList.some(function (item) {
                        return item == suffix;
                      });
                    } else if (searchParams.type == 'pic') {
                      var imgList = [
                        'png',
                        'jpg',
                        'jpeg',
                        'bmp',
                        'gif',
                        'webp',
                      ];
                      // 进行图片匹配
                      result = imgList.some(function (item) {
                        return item == suffix;
                      });
                    } else if (searchParams.type == 'document') {
                      var typeList = [
                        'txt',
                        'xls',
                        'xlsx',
                        'doc',
                        'docx',
                        'pdf',
                        'ppt',
                        'pptx',
                        'js',
                      ];
                      // 进行图片匹配
                      result = typeList.some(function (item) {
                        return item == suffix;
                      });
                    } else {
                      return true;
                    }
                    if (!result) {
                      message.error('文件类型上传错误！');
                    }
                    return result;
                  }}
                  {...props}
                >
                  <Button type="primary" icon={<UploadOutlined />}>
                    上传
                  </Button>
                </Upload>,
                <Button
                  key="refresh"
                  icon={<ReloadOutlined />}
                  onClick={() => loadFileList()}
                />,
              ];
            },
          }}
          span={7}
        >
          <ProFormText
            name="search"
            label="文件名称"
            placeholder="请输入文件名称"
          />
          <ProFormRadio.Group
            name="type"
            label="类型"
            radioType="button"
            options={[
              {
                label: '视频',
                value: 'video',
              },
              {
                label: '图片',
                value: 'pic',
              },
              {
                label: '文档',
                value: 'document',
              },
              {
                label: '其他',
                value: 'other',
              },
            ]}
          />
        </QueryFilter>
      </div>
      <div
        style={{
          background: 'rgba(25, 38, 86, 0.9)',
          height: 'calc(100% - 96px)',
          borderRadius: '6px',
          overflowY: 'auto',
        }}
      >
        <Row gutter={[16, 16]} className={styles.fileList}>
          {list?.map((d) => (
            <Col key={d.id} xl={6} xxl={4}>
              <div className={styles.file}>
                <div
                  className={styles.fileImage}
                  onClick={() => {
                    if (searchParams.type === 'video') {
                      console.log('d.fileUrl', d.fileUrl);
                      window.tm?.ipcRenderer.send(
                        'previewVideo',
                        `${d.fileUrl.replaceAll('/mp4', '')}`,
                        d.fileName,
                      );
                    }
                  }}
                >
                  {searchParams.type === 'video' && (
                    <img className={styles.imgIcon} src="/img/video.svg" />
                  )}
                  {searchParams.type === 'document' && (
                    <img className={styles.imgIcon} src="/img/doc.svg" />
                  )}
                  {searchParams.type === 'other' && (
                    <img className={styles.imgIcon} src="/img/file.svg" />
                  )}
                  {searchParams.type === 'pic' && (
                    <Image
                      width="300px"
                      height="230px"
                      src={`${d.fileUrl}`}
                      preview={{ maskClassName: styles.previewImg }}
                    />
                  )}
                </div>
                <div className={styles.fileToolBar}>
                  <div className={styles.btnGroup}>
                    <Popconfirm
                      key="delete"
                      title="确认删除吗？"
                      onConfirm={async () => {
                        const { data, success } = await deleteMaterialFile(
                          peerServer,
                          d.id,
                        );
                        if (success) {
                          loadFileList();
                          _message.success('删除成功');
                        } else {
                          _message.error('删除失败');
                        }
                      }}
                    >
                      <Button
                        className={styles.deleteBtn}
                        type="primary"
                        icon={<DeleteOutlined />}
                      />
                    </Popconfirm>
                    <Button
                      className={styles.downloadBtn}
                      type="primary"
                      icon={<DownloadOutlined />}
                      onClick={() => {
                        // window.open(`${panServer}${d.fileUrl}`, '_blank');
                        const link = document.createElement('a');
                        link.style.display = 'none';
                        link.href = `${d.fileUrl}`;
                        // link.href = `${panServer}${d.fileUrl}`;
                        link.setAttribute('download', d.fileName);
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                      }}
                    />
                  </div>
                </div>
                <div className={styles.fileTitle}>{d.fileName}</div>
              </div>
            </Col>
          ))}
        </Row>
      </div>
    </div>
  );
};

export default MaterialFile;
